/**
 * Booking tour js
 *
 * @author physcode
 * @version 2.0.0
 */

;(function ($) {
	'use strict';
	var date_validate = [];
	var date_can_book = [];
	var date_arr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
	var month_arr = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
	var tour_days = '';
	var date_book = '';
	var load_notify = false;

	let el_tourBookingForm = null;
	let el_tour_date_checkin_checkout = null;
	let el_tour_datepicker_range_checkin_checkout = null;
	let el_input_tour_datepicker_range_checkin_checkout = null;
	let el_number_ticket = null;
	let el_price_ticket = null;
	let el_show_price_ticket = null;
	let el_number_children = null;
	let el_price_children = null;
	let el_show_price_children = null;
	let el_field_travel_booking = null;
	let el_input_date_book = null;
	let tour_have_children_ticket = false;
	let el_tour_date_starts_after = null;
	let el_tour_duration_number = null;
	let el_tour_group_discount_data_phys = null;
	let el_label_tour_group_discount = null;

	$.fn.tour_booking_init = function () {
		el_tourBookingForm = $('form#tourBookingForm');

		if (el_tourBookingForm.length > 0) {
			$.fn._get_elms_tour_booking_form();
			$.fn.tour_booking();

			if (getCookie('info_user')) {
				let info_user = JSON.parse(getCookie('info_user'));
				$('input[name=first_name]').val(info_user.first_name);
				$('input[name=last_name]').val(info_user.last_name);
				$('input[name=email_tour]').val(info_user.email);
				$('input[name=phone]').val(info_user.phone);

				// for billing
				$('input[name=billing_first_name]').val(info_user.first_name);
				$('input[name=billing_last_name]').val(info_user.last_name);
				$('input[name=billing_email]').val(info_user.email);
				$('input[name=billing_phone]').val(info_user.phone);
			}
		}
	};

	$.fn._get_elms_tour_booking_form = function () {
		el_price_ticket = el_tourBookingForm.find('input[name=price_ticket]');
		el_number_ticket = el_tourBookingForm.find('input[name=number_ticket]');
		el_show_price_ticket = el_tourBookingForm.find('.price_ticket');
		el_number_children = el_tourBookingForm.find('input[name=number_children]');
		el_price_children = el_tourBookingForm.find('input[name=price_children]');
		el_field_travel_booking = el_tourBookingForm.find('.field-travel-booking');
		el_show_price_children = el_tourBookingForm.find('.price_child');
		el_tour_date_checkin_checkout = el_tourBookingForm.find('.tour_date_checkin_checkout');
		el_input_date_book = el_tourBookingForm.find('input[name=date_book]');
		el_tour_date_starts_after = el_tourBookingForm.find('input[name=tour_date_starts_after]');
		el_tour_duration_number = el_tourBookingForm.find('input[name=tour_duration_number]');
		el_tour_group_discount_data_phys = el_tourBookingForm.find('input[name=tour_group_discount_data_phys]');
		el_label_tour_group_discount = el_tourBookingForm.find('.label-tour-group-discount');

		if (el_number_children.length > 0) {
			tour_have_children_ticket = true;
		}
	};

	$._dates_disable = null;
	$._max_year = null;
	$._date_format_default = 'yy/mm/dd';
	$._date_format_default_datepicker_range = 'YYYY/MM/DD';
	$._tour_date_format = null;
	// $._date_format_convert_php_js = {};
	// $._date_format_convert_php_js['d/m/Y'] = 'dd/mm/yy';
	// $._date_format_convert_php_js['Y/m/d'] = 'yy/mm/dd';
	// $._date_format_convert_php_js['D, d M, Y'] = 'D, d M, yy';
	// $._date_format_convert_php_js['l, d F, Y'] = 'DD, d MM, yy';
	$._date_format_convert_php_js = {
		'Y/m/d'    : 'yy/mm/dd',
		'Y-m-d'    : 'yy-mm-dd',
		'd/m/Y'    : 'dd/mm/yy',
		'd-m-Y'    : 'dd-mm-yy',
		'm/d/Y'    : 'mm/dd/yy',
		'm-d-Y'    : 'mm-dd-yy',
		'D, d M, Y': 'D, d M, yy',
		'l, d F, Y': 'DD, d MM, yy',
	};
	$._tour_date_check_in_old = '';
	let phys_tour_price_dates_type = null;
	let el_tour_date_check_in = null;
	let el_tour_date_check_out = null;
	$._tour_price_of_dates_option = null;

	$.fn.tour_booking = function () {
		let tour_date_starts_after = 0;
		let date_now = new Date();
		let el_phys_tour_dates_disable = el_tourBookingForm.find('input[name=phys_tour_dates_disable]');
		let el_phys_tour_max_year_enable = el_tourBookingForm.find('input[name=phys_tour_max_year_enable]');
		// let el_tour_date_format = el_tourBookingForm.find('input[name=tour_date_format]');
		phys_tour_price_dates_type = el_tourBookingForm.find('input[name=phys_tour_price_dates_type]').val();
		let el_phys_tour_price_of_dates_option = el_tourBookingForm.find('input[name=phys_tour_price_of_dates_option]');

		$.fn.update_tour_total_price();

		if (el_phys_tour_price_of_dates_option.length > 0 && el_phys_tour_price_of_dates_option.val() !== '' && el_phys_tour_price_of_dates_option.val() !== '{}') {
			$._tour_price_of_dates_option = JSON.parse(el_phys_tour_price_of_dates_option.val());
		}

		/*** Set date format ***/
		$._tour_date_format = $._date_format_default;

		if ($._date_format_convert_php_js[travel_booking.tour_date_format] !== undefined) {
			$._tour_date_format = $._date_format_convert_php_js[travel_booking.tour_date_format]
		}

		$._max_year = el_phys_tour_max_year_enable.val();

		if (el_phys_tour_dates_disable.length > 0 && el_phys_tour_dates_disable.val() !== '') {
			$._dates_disable = JSON.parse(el_phys_tour_dates_disable.val());
		}

		/*** Start After ***/
		if (el_tour_date_starts_after.length > 0) {
			if (el_tour_date_starts_after.val() != '' && parseFloat(el_tour_date_starts_after.val()) !== 0) {
				tour_date_starts_after = parseFloat(el_tour_date_starts_after.val());

				let new_date = new Date();
				date_now.setDate(new_date.getDate() + tour_date_starts_after);
			}
		}

		let option_date_picker = {
			dateFormat: $._tour_date_format,
			minDate   : date_now,
			yearRange : date_now.getFullYear() + ':' + $._max_year,
		};

		if ($._dates_disable !== null) {
			option_date_picker.beforeShowDay = function (date) {
				date = $.fn._convert_date_obj_by_format_default(date);

				let indexOf = $._dates_disable.indexOf(date);

				if (indexOf > -1) {
					return [false, "", "Unavailable"];
				} else {
					return [true, "", "Available"];
				}
			}
		}

		// Date book
		if (el_input_date_book.length > 0) {
			delete el_input_date_book.beforeShowDay;
			if (jQuery().datepicker) {
				el_input_date_book.datepicker(option_date_picker);
				let duration = parseInt(el_tour_duration_number.val());

				let function_anonymous_beforeShowDays = function (date) {
					$._tour_dates_choose = [];

					if (el_input_date_book.val() !== '') {
						let date_start_obj = new Date($.fn._convert_date_to_format_default(el_input_date_book.val()));
						let date_next = date_start_obj;
						let start_date = $.fn._convert_date_obj_by_format_default(date_start_obj);
						let end_date_obj = new Date($.fn._convert_date_to_format_default(el_input_date_book.val()));
						end_date_obj.setDate(date_start_obj.getDate() + duration);
						let end_date = $.fn._convert_date_obj_by_format_default(end_date_obj);

						while (date_next < end_date_obj) {
							console.log(date_next);
							let date_string_by_format_default = $.fn._convert_date_obj_by_format_default(date_next);
							$._tour_dates_choose.push(date_string_by_format_default);
							date_next.setDate(date_next.getDate() + 1);
						}

						date = $.fn._convert_date_obj_by_format_default(date);
						let indexOf = $._tour_dates_choose.indexOf(date);

						if ($._dates_disable !== null) {
							let indexOfDatesDisable = $._dates_disable.indexOf(date);

							if (indexOf > -1) {
								if (indexOfDatesDisable > -1) {
									if (date == start_date) {
										return [false, "date-picked start-date", "Unavailable"];
									} else if (date == end_date) {
										return [false, "date-picked end-date", "Unavailable"];
									} else {
										return [false, "date-picked", "Unavailable"];
									}
								} else {
									if (date == start_date) {
										return [true, "date-picked start-date", "Available"];
									} else if (date == end_date) {
										return [true, "date-picked end-date", "Available"];
									} else {
										return [true, "date-picked", "Available"];
									}
								}
							} else {
								if (indexOfDatesDisable > -1) {
									return [false, "", "Unavailable"];
								} else {
									return [true, "", "Available"];
								}
							}
						} else {
							if (indexOf > -1) {
								if (date == start_date) {
									return [true, "date-picked start-date", ""];
								} else if (date == end_date) {
									return [true, "date-picked end-date", ""];
								} else {
									return [true, "date-picked", ""];
								}
							} else {
								return [true, "", ""];
							}
						}
					} else {
						date = $.fn._convert_date_obj_by_format_default(date);
						if ($._dates_disable !== null) {
							let indexOf = $._dates_disable.indexOf(date);

							if (indexOf > -1) {
								return [false, "", "Unavailable"];
							} else {
								return [true, "", "Available"];
							}
						} else {
							return [true, "", "Available"];
						}
					}
				};

				el_input_date_book.datepicker('option', 'beforeShowDay', function_anonymous_beforeShowDays);
			}
		}

		// Date checkin & checkout
		if (el_tour_date_checkin_checkout.length > 0) {
			el_tour_date_check_in = el_tour_date_checkin_checkout.find('input[name=tour_date_check_in]');
			el_tour_date_check_out = el_tour_date_checkin_checkout.find('input[name=tour_date_check_out]');
			if (jQuery().datepicker) {
				el_tour_date_check_out.datepicker(option_date_picker);

				el_tour_date_check_in.datepicker(option_date_picker);

				el_tour_date_check_in.datepicker('option', 'onClose', function (date) {
					// console.log(date);
					if (date !== '') {
						let date_next = new Date($.fn._convert_date_to_format_default(date));

						date_next.setDate(date_next.getDate() + 1);

						el_tour_date_check_out.datepicker('option', 'minDate', date_next);

						$.fn.update_tour_total_price();

						if (date !== $._tour_date_check_in_old) {
							$._tour_date_check_in_old = date;
							// el_tour_date_check_out.focus();
						}
					}
				});

				el_tour_date_check_out.datepicker('option', 'onClose', function (date) {
					$.fn.update_tour_total_price();
				});
			}
		}

		// Date checkin & checkout range
		el_tour_datepicker_range_checkin_checkout = el_tourBookingForm.find('.tour-datepicker-range-checkin-checkout');
		if (el_tour_datepicker_range_checkin_checkout.length > 0) {
			el_input_tour_datepicker_range_checkin_checkout = el_tour_datepicker_range_checkin_checkout.find('input[name=tour_datepicker_range_checkin_checkout]');

			let option_datepicker_range = {
				minDate: date_now,
				"opens": "left",
				drops  : 'up',
				locale : {
					"format": $._date_format_default_datepicker_range,
				}
			};

			el_input_tour_datepicker_range_checkin_checkout.daterangepicker(option_datepicker_range, function (start, end) {
				console.log(start, end);
			});
		}

		if (el_field_travel_booking.length > 0) {
			el_field_travel_booking.on('change keyup', function (i) {
				$.fn.update_tour_total_price();
			});
		}
	};

	$.fn.update_tour_total_price = function () {
		var el_show_total_price = $('.total_price');
		var total_price = 0;
		var el_deposit_amount = $('.deposit_amount_per');
		var el_deposit_type = $('input[name=deposit_type]');
		var deposit_amount = $('input[name=deposit_amount]');
		var woocommerce_price_num_decimals = $('input[name=woocommerce_price_num_decimals]');
		var num_decimals = woocommerce_price_num_decimals.val();
		let el_field_travel_booking = $('.field-travel-booking');
		let el_tour_variations_options = $('input[name=tour_variations_options]');

		/*** Ticket default ***/
		total_price += el_price_ticket.val() * el_number_ticket.val();

		/*** Children ***/
		if (tour_have_children_ticket) {
			total_price += el_price_children.val() * el_number_children.val();
		}

		/*** Get price by dates ***/
		let price_dates_tour_variation = {};
		if (el_tour_date_checkin_checkout.length > 0) {
			if ($._tour_price_of_dates_option !== null) {

				if (phys_tour_price_dates_type !== null &&
					phys_tour_price_dates_type === 'price_dates_range' &&
					$._tour_price_of_dates_option.price_dates_range !== undefined) {

					let tour_price_dates_range = $._tour_price_of_dates_option.price_dates_range;

					if (el_tour_date_check_in.val() !== '' && el_tour_date_check_out.val() !== '') {
						let child_price = 0;
						let adult_price = 0;
						let date_check_in = $.fn._convert_date_to_format_default(el_tour_date_check_in.val());
						let date_check_out = $.fn._convert_date_to_format_default(el_tour_date_check_out.val());
						let el_number_day = $('.number-day');
						let tour_price_dates_range_length = Object.keys(tour_price_dates_range).length;

						// console.log(tour_price_dates_range_length);

						// console.log(tour_price_dates_range);

						// Get total days
						let total_night = $.fn._calculate_total_night(date_check_in, date_check_out);
						// let total_days = $.fn._calculate_total_days(date_check_in, date_check_out);
						el_number_day.text(total_night);

						// show rage dates choose
						$.fn._show_range_dates_choose(date_check_in, date_check_out);

						let date_check_in_obj = new Date(date_check_in);
						let date_check_out_obj = new Date(date_check_out);
						let date_next = date_check_in_obj;

						while (date_next < date_check_out_obj) {
							// console.log(date_next);
							let count_tour_price_dates_range = 1;

							if (tour_price_dates_range_length > 0) {
								$.each(tour_price_dates_range, function (k, v) {
									let start_date = new Date(v.start_date);
									let end_date = new Date(v.end_date);
									let flag_same = false;

									if (date_next >= start_date && date_next <= end_date) {
										$.each(v.prices, function (k_price, v_price) {
											let price = v_price.price;

											if (tour_have_children_ticket && k_price === 'child_price_dates') {
												if (tour_have_children_ticket) {

													if (price === '' || isNaN(price)) {
														price = parseFloat(el_price_children.val());
													}

													child_price += parseFloat(price);

													el_show_price_children.text(child_price);
												}
											} else if (k_price === 'regular_price_dates' && price !== '') {
												if (price === '' || isNaN(price)) {
													price = parseFloat(el_price_ticket.val());
												}

												adult_price += parseFloat(price);
											} else if (k_price !== 'child_price_dates' && k_price !== 'regular_price_dates') {
												console.log('price variation');
												if (el_tour_variations_options.length > 0 && el_field_travel_booking.length > 0) {
													let tour_variation_options = JSON.parse(el_tour_variations_options.val());

													$.each(v_price, function (k_attr, v_attr) {
														if (price_dates_tour_variation[k_price] === undefined) {
															price_dates_tour_variation[k_price] = {};
														}

														if (price_dates_tour_variation[k_price][k_attr] === undefined) {
															//Todo: get price of variation if isNaN
															if (v_attr.price === '' || isNaN(v_attr.price)) {
																v_attr.price = tour_variation_options[k_price]["variation_attr"][k_attr]['price'];
															}

															price_dates_tour_variation[k_price][k_attr] = parseFloat(v_attr.price);
														} else {
															//Todo: get price of variation if isNaN
															if (v_attr.price === '' || isNaN(v_attr.price)) {
																v_attr.price = tour_variation_options[k_price]["variation_attr"][k_attr]['price'];
															}

															price_dates_tour_variation[k_price][k_attr] += parseFloat(v_attr.price);
														}
													});
												}
											}
										});

										flag_same = true;
									}

									if (flag_same) {
										return;
									}

									if (count_tour_price_dates_range === tour_price_dates_range_length && !flag_same) {
										console.log('date not in price dates option');

										adult_price += parseFloat(el_price_ticket.val());

										if (tour_have_children_ticket) {
											child_price += parseFloat(el_price_children.val());
										}

										if (el_tour_variations_options.length > 0 && el_field_travel_booking.length > 0) {
											let tour_variation_options = JSON.parse(el_tour_variations_options.val());
											console.log(tour_variation_options);

											$.each(tour_variation_options, function (k_variation, v_variation) {
												if (price_dates_tour_variation[k_variation] === undefined) {
													price_dates_tour_variation[k_variation] = {};
												}

												if (v_variation.set_price == 1) {
													$.each(v_variation.variation_attr, function (k_attr, v_attr) {
														if (price_dates_tour_variation[k_variation][k_attr] === undefined) {
															price_dates_tour_variation[k_variation][k_attr] = parseFloat(v_attr.price);
														} else {
															price_dates_tour_variation[k_variation][k_attr] += parseFloat(v_attr.price);
														}
													});
												}
											});
										}
									}

									count_tour_price_dates_range++;
								});
							} else {
								adult_price += parseFloat(el_price_ticket.val());

								if (tour_have_children_ticket) {
									child_price += parseFloat(el_price_children.val());
								}
							}

							date_next.setDate(date_next.getDate() + 1);
						}

						console.log(price_dates_tour_variation);

						// Show price
						el_show_price_ticket.text(adult_price);

						if (tour_have_children_ticket) {
							el_show_price_children.text(child_price);
						}

						// Total price when date change
						let total_price_ticket = parseFloat(adult_price) * el_number_ticket.val();
						let total_price_children = 0;

						if (tour_have_children_ticket) {
							total_price_children = parseFloat(child_price) * el_number_children.val();
						}

						total_price = total_price_ticket + total_price_children;
					}
				} else if (phys_tour_price_dates_type !== null &&
					phys_tour_price_dates_type === 'price_multiple_dates' &&
					$._tour_price_of_dates_option.price_multiple_dates !== undefined
				) {

				}
			} else {
				if (el_tour_date_check_in !== null &&
					el_tour_date_check_in.val() !== '' &&
					el_tour_date_check_out !== null &&
					el_tour_date_check_out.val() !== '') {

					let child_price = 0;
					let adult_price = 0;
					let date_check_in = $.fn._convert_date_to_format_default(el_tour_date_check_in.val());
					let date_check_out = $.fn._convert_date_to_format_default(el_tour_date_check_out.val());
					let el_number_day = $('.number-day');

					// Get total night
					let total_night = $.fn._calculate_total_night(date_check_in, date_check_out);
					// Get total days
					let total_days = $.fn._calculate_total_days(date_check_in, date_check_out);
					el_number_day.text(total_night);

					// show rage dates choose
					$.fn._show_range_dates_choose(date_check_in, date_check_out);

					let date_check_in_obj = new Date(date_check_in);
					let date_check_out_obj = new Date(date_check_out);
					let date_next = date_check_in_obj;

					while (date_next < date_check_out_obj) {
						adult_price += parseFloat(el_price_ticket.val());

						if (tour_have_children_ticket) {
							child_price += parseFloat(el_price_children.val());
						}

						if (el_tour_variations_options.length > 0 && el_field_travel_booking.length > 0) {
							let tour_variation_options = JSON.parse(el_tour_variations_options.val());
							console.log(tour_variation_options);

							$.each(tour_variation_options, function (k_variation, v_variation) {
								if (price_dates_tour_variation[k_variation] === undefined) {
									price_dates_tour_variation[k_variation] = {};
								}

								if (v_variation.set_price == 1) {
									$.each(v_variation.variation_attr, function (k_attr, v_attr) {
										if (price_dates_tour_variation[k_variation][k_attr] === undefined) {
											price_dates_tour_variation[k_variation][k_attr] = parseFloat(v_attr.price);
										} else {
											price_dates_tour_variation[k_variation][k_attr] += parseFloat(v_attr.price);
										}
									});
								}
							});
						}

						date_next.setDate(date_next.getDate() + 1);
					}

					// Show price
					el_show_price_ticket.text(adult_price);

					if (tour_have_children_ticket) {
						el_show_price_children.text(child_price);
					}

					// Total price when date change
					let total_price_ticket = parseFloat(adult_price) * el_number_ticket.val();
					let total_price_children = 0;
					if (tour_have_children_ticket) {
						total_price_children = parseFloat(child_price) * el_number_children.val();
					}

					total_price = total_price_ticket + total_price_children;
				}
			}
		}

		// Variation
		if (el_tour_variations_options.length > 0 && el_field_travel_booking.length > 0) {
			let total_price_variation = 0;

			$.each(el_field_travel_booking, function (i) {
				let el = $(this);
				let el_tour_variation_item = el.closest('.tour-variation-item');

				if (el_tour_variation_item.length > 0) {
					let variation_id = el_tour_variation_item.data('variation-id');
					let variation_set_price = el_tour_variation_item.data('set_price');
					let variation_type = el_tour_variation_item.data('type_variation');
					let variation_required = el_tour_variation_item.data('required');
					let variation_attr_id = 0;
					let price = 0;

					switch (variation_type) {
						case 'quantity':
							variation_attr_id = parseInt(el.attr('name'));
							// console.log(variation_attr_id);

							if (variation_set_price === 1) {
								price = parseFloat(el.filter('[name="' + variation_attr_id + '"]').data('attr-price'));

								// Price dates tour variation
								if (price_dates_tour_variation[variation_id] !== undefined &&
									price_dates_tour_variation[variation_id][variation_attr_id] !== undefined) {
									price = price_dates_tour_variation[variation_id][variation_attr_id];
								}

								price = price * el.val();
							}

							total_price_variation += price;

							break;
						case 'select':
							variation_attr_id = parseInt(el.val());

							if (variation_attr_id > 0) {
								if (variation_set_price === 1) {
									price = parseFloat(el.find('option').filter('[value="' + variation_attr_id + '"]').data('attr-price'));

									// Price dates tour variation
									if (price_dates_tour_variation[variation_id] !== undefined &&
										price_dates_tour_variation[variation_id][variation_attr_id] !== undefined) {
										price = price_dates_tour_variation[variation_id][variation_attr_id];
									}
								}
							}

							total_price_variation += price;
							break;
						case 'checkbox':
							if (el.is(':checked')) {
								variation_attr_id = parseInt(el.val());

								if (variation_set_price === 1) {
									price = parseFloat(el.filter('[value="' + variation_attr_id + '"]').data('attr-price'));
								}

								total_price_variation += price;
							}
							break;
						case 'radio':
							if (el.is(':checked')) {
								variation_attr_id = parseInt(el.val());

								if (variation_set_price === 1) {
									price = parseFloat(el.filter('[value="' + variation_attr_id + '"]').data('attr-price'));
								}

								total_price_variation += price;
							}
							break;
						default:
							break;
					}
				}
			});

			total_price += parseFloat(total_price_variation);
		}

		// Group discount
		if (el_tour_group_discount_data_phys.length > 0) {
			let el_show_val_discount = el_label_tour_group_discount.find('.val-discount');
			let el_currency_group_discount = el_label_tour_group_discount.find('.woocommerce-Price-currencySymbol');
			let el_show_total_people = el_label_tour_group_discount.find('.total-people');

			if (el_tour_group_discount_data_phys.val() !== '') {
				try {
					let tour_group_discount_data_phys_obj = JSON.parse(el_tour_group_discount_data_phys.val());
					let total_person = parseInt(el_number_ticket.val());

					/*** Children ***/
					if (tour_have_children_ticket) {
						total_person += parseInt(el_number_children.val());
					}

					let customer_number_match = 0;
					let discount_val = 0;

					$.each(tour_group_discount_data_phys_obj, function (k, v) {
						let number_customer = parseInt(v.number_customer);

						if (number_customer <= total_person && customer_number_match < number_customer) {
							customer_number_match = number_customer;
							discount_val = v.discount;
						}
					});

					if (customer_number_match !== 0) {
						let patter = /\%$/;

						el_show_val_discount.text(discount_val);
						el_show_total_people.text(total_person);
						el_label_tour_group_discount.show();

						if (patter.test(discount_val)) {
							el_currency_group_discount.hide();
							discount_val = parseFloat(discount_val);

							total_price = total_price - (total_price * discount_val / 100);
						} else {
							discount_val = parseFloat(discount_val);
							el_show_val_discount.text(discount_val.toFixed(num_decimals));
							el_currency_group_discount.show();
							total_price = total_price - discount_val;
						}
					} else {
						el_label_tour_group_discount.hide();
					}
				} catch (e) {
					console.error(e);
				}
			}
		}

		el_show_total_price.text(total_price.toFixed(num_decimals));
	};

	$.fn.tour_booking_submit = function () {
		$('.btn-booking').on('click', function (e) {
			e.preventDefault();
			let el_btn_booking = $(this);
			let flag_errors = false;
			var input_first_name = $('input[name=first_name]');
			var input_last_name = $('input[name=last_name]');
			var input_email = $('input[name=email_tour]');
			var input_phone = $('input[name=phone]');
			var input_qty = $('input[name=number_ticket]');
			var qty_tour = parseInt(input_qty.val());
			var tb_phys_ajax_url = $('input[name=url_home]').val();
			var el_deposit_radio = $('input[name=deposit_radio]');
			var max_qty_per = parseInt(input_qty.attr('max'));
			let el_tour_variation_item = $('.tour-variation-item');
			let el_tour_variations_options = $('input[name=tour_variations_options]');

			if (input_first_name.length > 0) {
				if (input_first_name.val().length == 0) {
					input_first_name.attr('placeholder', travel_booking.message_er_first_name);
					input_first_name.addClass('error');
					return;
				}
			}

			if (input_last_name.length > 0) {
				if (input_last_name.val().length == 0) {
					input_last_name.attr('placeholder', travel_booking.message_er_last_name);
					input_last_name.addClass('error');
					return;
				}
			}

			if (input_email.length > 0) {
				if (!checkValidateEmail(input_email.val())) {
					input_email.attr('placeholder', travel_booking.message_er_email);
					input_email.addClass('error');
					input_email.val('');
					return;
				}
			}

			if (input_phone.length > 0) {
				if (input_phone.val().length == 0) {
					input_phone.attr('placeholder', travel_booking.message_er_phone);
					input_phone.addClass('error');
					return;
				}
			}

			if (el_input_date_book.length > 0) {
				if (el_input_date_book.val().length == 0) {
					el_input_date_book.attr('placeholder', travel_booking.message_er_date);
					el_input_date_book.addClass('error');
					return;
				}
			}

			if (isNaN(qty_tour) || qty_tour <= 0) {
				input_qty.val(1);

			} else if (qty_tour > max_qty_per) {
				return;
			}

			function checkValidateEmail(email) {
				var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
				return regex.test(email);
			}

			// run ajax add to cart
			if (!el_btn_booking.hasClass('disable')) {
				var data = {
					nonce       : $('input[name=nonce]').val(),
					tour_id     : $('input[name=tour_id]').val(),
					date_booking: el_input_date_book.val(),
				};

				data.number_ticket = input_qty.val();

				/*** Children ***/
				if (el_number_children.length > 0) {
					let number_children = el_number_children.val();

					if (isNaN(number_children) || parseFloat(number_children) < 0) {
						number_children = 0;
					}

					data.number_children = number_children;
				}

				/*** Variation ***/
				if (el_tour_variations_options.length > 0) {
					data.tour_variations = {};

					$.each(el_tour_variation_item, function (i) {
						let el_tour_variation_item = $(this);
						let variation_id = el_tour_variation_item.data('variation-id');
						let variation_type = el_tour_variation_item.data('type_variation');
						let variation_required = parseInt(el_tour_variation_item.data('required'));
						let el_variation_attr_field = el_tour_variation_item.find('.field-travel-booking');
						let total_el_variation_attr_field = el_variation_attr_field.length;
						let variation_attr_id = 0;

						if (data.tour_variations[variation_id] === undefined) {
							data.tour_variations[variation_id] = {};
						}

						if (variation_type === 'quantity' && !flag_errors) {
							let flag_error_variation_quantity = true;

							$.each(el_variation_attr_field, function (i) {
								let el_variation_attr_field = $(this);
								variation_attr_id = parseInt(el_variation_attr_field.attr('name'));

								if (parseFloat(el_variation_attr_field.val()) > 0) {
									data.tour_variations[variation_id][variation_attr_id] = {};
									data.tour_variations[variation_id][variation_attr_id].quantity = el_variation_attr_field.val();

									flag_error_variation_quantity = false;
								}

								if (variation_required) {
									if (flag_error_variation_quantity && i === total_el_variation_attr_field - 1) {
										flag_errors = true;
										el_tour_variation_item.addClass('errors');
										setTimeout(function () {
											el_tour_variation_item.removeClass('errors')
										}, 2000);
									}
								}
							});
						} else if (variation_type === 'select' && !flag_errors) {
							let el_variation_attr_field = el_tour_variation_item.find('.field-travel-booking');
							variation_attr_id = parseInt(el_variation_attr_field.val());

							if (variation_attr_id > 0) {
								data.tour_variations[variation_id][variation_attr_id] = {};
							} else {
								if (variation_required) {
									flag_errors = true;
									el_variation_attr_field.addClass('errors');
									setTimeout(function () {
										el_variation_attr_field.removeClass('errors')
									}, 2000);
								}
							}

						} else if (variation_type === 'checkbox' && !flag_errors) {
							let flag_errors_variation_checkbox = true;

							$.each(el_variation_attr_field, function (i) {
								let el_variation_attr_field = $(this);
								if (el_variation_attr_field.is(':checked')) {
									variation_attr_id = parseInt(el_variation_attr_field.val());

									data.tour_variations[variation_id][variation_attr_id] = {};

									flag_errors_variation_checkbox = false;
									flag_errors = false;
								}

								if (variation_required) {
									if (flag_errors_variation_checkbox && i === total_el_variation_attr_field - 1) {
										flag_errors = true;
										el_tour_variation_item.addClass('errors');
										setTimeout(function () {
											el_tour_variation_item.removeClass('errors')
										}, 2000);
									}
								}
							});
						} else if (variation_type === 'radio' && !flag_errors) {
							let flag_errors_variation_radio = true;

							$.each(el_variation_attr_field, function (i) {
								let el_variation_attr_field = $(this);

								if (el_variation_attr_field.is(':checked')) {
									variation_attr_id = parseInt(el_variation_attr_field.val());
									data.tour_variations[variation_id][variation_attr_id] = {};

									flag_errors_variation_radio = false;
									flag_errors = false;
								}

								if (variation_required) {
									if (flag_errors_variation_radio && i === total_el_variation_attr_field - 1) {
										flag_errors = true;
										el_tour_variation_item.addClass('errors');
										setTimeout(function () {
											el_tour_variation_item.removeClass('errors')
										}, 2000);
									}
								}
							});
						}
					});

					console.log(data.tour_variations);

					data.tour_variations = JSON.stringify((data.tour_variations));
				}

				/*** Price dates ***/
				if (el_tour_date_checkin_checkout.length > 0) {
					if (el_tour_date_check_in.length > 0 && el_tour_date_check_out.length > 0) {
						if (el_tour_date_check_in.val() === '') {
							el_tour_date_check_in.attr('placeholder', travel_booking.message_er_date_checkin);
							el_tour_date_check_in.addClass('error');
							return;
						}

						if (el_tour_date_check_out.val() === '') {
							el_tour_date_check_out.attr('placeholder', travel_booking.message_er_date_checkout);
							el_tour_date_check_out.addClass('error');
							return;
						}

						data.date_check_in = el_tour_date_check_in.val();
						data.date_check_out = el_tour_date_check_out.val();
					}
				}

				if (!flag_errors) {
					$('.spinner').show();
					el_btn_booking.addClass('disable');
					$.ajax({
						url     : tb_phys_ajax_url + '?tb-ajax=add_tour_to_cart_phys',
						type    : 'post',
						data    : data,
						dataType: 'json',
						success : function (result) {
							if (result.status === 'success') {
								var user_info = {
									first_name: input_first_name.val(),
									last_name : input_last_name.val(),
									email     : input_email.val(),
									phone     : input_phone.val()
								};

								document.cookie = "info_user=" + JSON.stringify(user_info) + '; path=/';
								window.location = $('input[name=checkout_url]').val();
							} else {
								alert(result.message);
							}
						}, error: function (result) {
							console.error(result);
						}
					}).done(function () {
						$('.spinner').hide();
						el_btn_booking.removeClass('disable');
					});
				}
			}
		});
	};

	$.fn.tour_orderby = function () {
		$('.tour-ordering').find('.orderby').on('change', function () {
			$('.tour-ordering').submit();
		});
	};

	$.fn.load_ajax_notify = function () {
		load_notify = false;
		var limit = $("input[name=notify_limit]").val();
		var tb_phys_ajax_url = $('input[name=url_home]').val();

		$.ajax({
			url     : tb_phys_ajax_url + "?tb-ajax=notify_new_order",
			type    : "post",
			data    : "limit=" + limit,
			dataType: "json",
			success : function (result) {
				if (result.status == "success") {
					$(".list-order-tour").html(result.html);
					load_notify = true;
				}
			}
		});
	};

	$.fn.load_notify_products_of_order = function () {
		var notify_available = $('input[name=notify_available]');
		if (notify_available.length) {
			load_notify = true;
			var refresh = $("input[name=notify_refresh]").val();
			if (refresh == "") {
				refresh = 10000;
			}

			setInterval(function () {
				if (load_notify) {
					$.fn.load_ajax_notify();
				}
			}, refresh);
		}
	};

	$.fn._convert_date_to_format_default = function (date_string) {
		let date_convert = '';
		let date = '';
		let month = '';
		let year = '';
		let separator_date = '/';

		if ($._tour_date_format === 'yy/mm/dd') {
			let date_arr = date_string.split('/');
			date = date_arr[2];
			month = date_arr[1];
			year = date_arr[0];
		} else if ($._tour_date_format === 'yy-mm-dd') {
			let date_arr = date_string.split('-');
			date = date_arr[2];
			month = date_arr[1];
			year = date_arr[0];
		} else if ($._tour_date_format === 'dd/mm/yy') {
			let date_arr = date_string.split('/');
			date = date_arr[0];
			month = date_arr[1];
			year = date_arr[2];
		} else if ($._tour_date_format === 'dd-mm-yy') {
			let date_arr = date_string.split('-');
			date = date_arr[0];
			month = date_arr[1];
			year = date_arr[2];
		} else if ($._tour_date_format === 'mm/dd/yy') {
			let date_arr = date_string.split('/');
			date = date_arr[1];
			month = date_arr[0];
			year = date_arr[2];
		} else if ($._tour_date_format === 'mm-dd-yy') {
			let date_arr = date_string.split('-');
			date = date_arr[1];
			month = date_arr[0];
			year = date_arr[2];
		} else if ($._tour_date_format === 'DD, d MM, yy') {
			let date_arr = date_string.split(',');
			let date_month_arr = date_arr[1].trim().split(' ');
			date = date_month_arr[0];
			month = month_arr.indexOf(date_month_arr[1]) + 1;

			if (parseInt(month) < 10) {
				month = '0' + month;
			}

			year = date_arr[2];
		}

		date_convert += year + separator_date + month + separator_date + date;

		// console.log(date_convert);

		return date_convert;
	};

	$.fn._convert_date_obj_by_format_default = function (date_obj) {
		let date_convert = '';
		let year = date_obj.getFullYear();
		let month = ("0" + (date_obj.getMonth() + 1)).slice(-2);
		let date = ("0" + date_obj.getDate()).slice(-2);

		date_convert += year + '/' + month + '/' + date;

		return date_convert;
	};

	$.fn._calculate_total_days = function (start_date, end_date) {
		let start_date_obj = new Date(start_date);
		let end_date_obj = new Date(end_date);
		let date_next = start_date_obj;
		let total_day = 0;

		while (date_next <= end_date_obj) {
			date_next.setDate(date_next.getDate() + 1);
			total_day += 1;
		}

		return total_day;
	};

	$.fn._calculate_total_night = function (start_date, end_date) {
		let start_date_obj = new Date(start_date);
		let end_date_obj = new Date(end_date);
		let date_next = start_date_obj;
		let total_day = 0;

		while (date_next < end_date_obj) {
			date_next.setDate(date_next.getDate() + 1);
			total_day += 1;
		}

		return total_day;
	};

	$.fn._show_range_dates_choose = function (start_date, end_date) {
		$._tour_dates_choose = [];
		let start_date_obj = new Date(start_date);
		start_date = $.fn._convert_date_obj_by_format_default(start_date_obj);
		let end_date_obj = new Date(end_date);
		end_date = $.fn._convert_date_obj_by_format_default(end_date_obj);
		let date_next = start_date_obj;

		end_date_obj.setDate(end_date_obj.getDate() + 1);

		while (date_next < end_date_obj) {
			// console.log(date_next);
			let date_string_by_format_default = $.fn._convert_date_obj_by_format_default(date_next);
			$._tour_dates_choose.push(date_string_by_format_default);
			date_next.setDate(date_next.getDate() + 1);
		}

		console.log(start_date, end_date);

		if (el_tour_date_check_in !== null && el_tour_date_check_out !== null) {

			let function_anonymous_beforeShowDay = function (date) {
				date = $.fn._convert_date_obj_by_format_default(date);
				// console.log(date);
				let indexOf = $._tour_dates_choose.indexOf(date);

				// console.log(indexOf, indexOfDatesDisable)
				if ($._dates_disable !== null) {
					let indexOfDatesDisable = $._dates_disable.indexOf(date);

					if (indexOf > -1) {
						if (indexOfDatesDisable > -1) {
							if (date == start_date) {
								return [false, "date-picked start-date", "Unavailable"];
							} else if (date == end_date) {
								return [false, "date-picked end-date", "Unavailable"];
							} else {
								return [false, "date-picked", "Unavailable"];
							}
						} else {
							if (date == start_date) {
								return [true, "date-picked start-date", "Available"];
							} else if (date == end_date) {
								return [true, "date-picked end-date", "Available"];
							} else {
								return [true, "date-picked", "Available"];
							}
						}
					} else {
						if (indexOfDatesDisable > -1) {
							return [false, "", "Unavailable"];
						} else {
							return [true, "", "Available"];
						}
					}
				} else {
					if (indexOf > -1) {
						if (date == start_date) {
							return [true, "date-picked start-date", ""];
						} else if (date == end_date) {
							return [true, "date-picked end-date", ""];
						} else {
							return [true, "date-picked", ""];
						}
					} else {
						return [true, "", ""];
					}
				}
			};
			if (jQuery().datepicker) {
				el_tour_date_check_in.datepicker('option', 'beforeShowDay', function_anonymous_beforeShowDay);

				el_tour_date_check_out.datepicker('option', 'beforeShowDay', function_anonymous_beforeShowDay);
			}
		} else {

		}
	};

	$.fn.filter_tour_price_widget = function () {
		let el_tour_price_range = document.getElementById('tour-price-range');

		if (el_tour_price_range) {
			let el_tour_min_price_show = $('.tour-min-price');
			let el_tour_max_price_show = $('.tour-max-price');
			let tour_start_price_filter = parseFloat($('input[name=tour_start_price_fitler]').val());
			let tour_end_price_filter = parseFloat($('input[name=tour_end_price_filter]').val());
			let el_tour_max_price = $('input[name=tour_max_price]');
			let el_tour_min_price = $('input[name=tour_min_price]');
			let min_price = parseFloat(el_tour_min_price.val());
			let max_price = parseFloat(el_tour_max_price.val());

			// console.log(min_price, max_price);

			noUiSlider.create(el_tour_price_range, {
				start  : [min_price, max_price],
				connect: true,
				range  : {
					'min': tour_start_price_filter,
					'max': tour_end_price_filter
				}
			});

			el_tour_price_range.noUiSlider.on('update', function (values) {
				// console.log(values);
				let min_price = values[0];
				let max_price = values[1];

				el_tour_min_price.val(min_price);
				el_tour_max_price.val(max_price);
				el_tour_min_price_show.text(min_price);
				el_tour_max_price_show.text(max_price);
			});

		}
	};

	function getCookie(cname) {
		var name = cname + "=";
		var decodedCookie = decodeURIComponent(document.cookie);
		var ca = decodedCookie.split(';');
		for (var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') {
				c = c.substring(1);
			}
			if (c.indexOf(name) == 0) {
				return c.substring(name.length, c.length);
			}
		}
		return "";
	}

})(jQuery, 'tour-booking-phys');

jQuery(function ($) {
	'use strict';
	$.fn.tour_booking_init();
	$.fn.tour_booking_submit();
	$.fn.tour_orderby();
	$.fn.load_notify_products_of_order();
	$.fn.filter_tour_price_widget();

	if ($('#tour_rating').length) {
		$('#tour_rating').barrating({
			theme: 'css-stars'
		});
	}

});